package com.salesys.gr.gui;

import java.io.IOException;

import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.SWT;
import com.salesys.gr.util.FrmHelper;
import com.salesys.gr.util.MsgBox;
import com.salesys.tony.service.UserService;

public class FrmUpdate {

	protected Shell FrmUpdate;

	/**
	 * Launch the application.
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			FrmUpdate window = new FrmUpdate();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		createContents();
		FrmUpdate.open();
		FrmUpdate.layout();
		while (!FrmUpdate.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
			if (checkUpdate() == 0) {
				break;
			}
		}
	}

	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		FrmUpdate = new Shell(SWT.TITLE);
		FrmUpdate.setSize(270, 160);
		FrmUpdate.setText("检查更新");

		// 窗口居中
		FrmUpdate.setLocation(new FrmHelper().setLocationCenter(FrmUpdate));

		Label lblCheckUpdate = new Label(FrmUpdate, SWT.CENTER);
		lblCheckUpdate.setBounds(10, 32, 234, 17);
		lblCheckUpdate.setText("正在检查服务器");

		Label lblCheckUpdate2 = new Label(FrmUpdate, SWT.CENTER);
		lblCheckUpdate2.setBounds(10, 66, 234, 17);
		lblCheckUpdate2.setText("是否存在新版本，请稍候...");
	}

	private int checkUpdate() {
		// 当前版本号
		String version = "1.5.0.1";
		// 最新版本号
		String nowVersion = "nodata";
		try {
			nowVersion = new UserService().checkUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (nowVersion.equals("nodata")) {
			new MsgBox().errorTip(FrmUpdate, "数据库连接失败，请检查网络连接是否正常");
			return 0;
		} else {
			// 检查版本号
			if (nowVersion.equals(version) == false) {
				new MsgBox().errorTip(FrmUpdate, "您使用的不是最新版本，请更新后使用\n\n点击确定下载最新版");
				try {
					Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler http://love-myeyes.com/wp-content/uploads/SaleSys.rar");
				} catch (IOException e) {
					e.printStackTrace();
				}
				FrmUpdate.close();
			} else {
				FrmUpdate.close();
				new FrmLogin().open();
			}
		}
		return 1;
	}
}
